<template>
  <div class="template-manage-container">
    <Sidebar 
      title="模版分类" 
      :items="sidebarItems" 
      :current-type="currentDataType"
      @select="handleTypeSelect"
    />

    <main class="template-main-content">
      <div class="toolbar">
        <h3>模版管理</h3>
        <button class="btn-secondary" @click="refreshList">🔄 刷新列表</button>
      </div>

      <div class="template-list-container">
        <div v-if="templates.length === 0" class="empty-state">
          暂无【{{ dataTypes[currentDataType] }}】类型的模版
        </div>
        
        <div v-else class="template-grid">
          <div v-for="tpl in templates" :key="tpl.id" class="template-card">
            <div class="card-header">
              <strong class="template-name">{{ tpl.name }}</strong>
              <span :class="['badge', tpl.isSystem ? 'badge-system' : 'badge-user']">
                {{ tpl.isSystem ? '系统预置' : '用户自定义' }}
              </span>
            </div>
            
            <div class="card-body">
              <div class="info-item">包含字段数: <b>{{ Object.keys(tpl.mappings).length }}</b></div>
              <div class="info-item example-text" :title="Object.keys(tpl.mappings).join(', ')">
                示例: {{ Object.keys(tpl.mappings).slice(0, 3).join(', ') }}...
              </div>
            </div>

            <div class="card-footer">
              <button class="btn-primary-outline" @click="handleView(tpl)">查看详情</button>
              <button v-if="!tpl.isSystem" class="btn-danger-outline" @click="handleDelete(tpl)">删除模版</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 模板详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="`模板详情 - ${currentTemplate?.name}`"
        width="600px"
      >
        <div v-if="currentTemplate" class="template-detail">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">模板名称：</span>
                <span class="value">{{ currentTemplate.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">数据类型：</span>
                <span class="value">{{ dataTypes[currentTemplate.dataType] }}</span>
              </div>
              <div class="info-item">
                <span class="label">模板类型：</span>
                <span class="value">{{ currentTemplate.isSystem ? '系统预置' : '用户自定义' }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>字段映射规则（{{ Object.keys(currentTemplate.mappings).length }} 个）</h4>
            <el-table :data="mappingList" border style="width: 100%">
              <el-table-column prop="source" label="原始列名" width="180" />
              <el-table-column prop="target" label="系统字段名" width="180" />
              <el-table-column prop="description" label="字段描述" />
            </el-table>
          </div>
        </div>

        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Sidebar from '@/components/Sidebar.vue'
import { TemplateManager } from '@/utils/templateManager'
import { dataTypes, dataTypeIcons, fieldDict } from '@/utils/fields'

const currentDataType = ref('bank')
const allTemplates = ref({})
const dialogVisible = ref(false)
const currentTemplate = ref(null)

const sidebarItems = computed(() => {
  return Object.keys(dataTypes).map(type => ({
    type,
    label: dataTypes[type],
    icon: dataTypeIcons[type]
  }))
})

const templates = computed(() => {
  return Object.values(allTemplates.value).filter(t => t.dataType === currentDataType.value)
})

const mappingList = computed(() => {
  if (!currentTemplate.value) return []
  const mappings = currentTemplate.value.mappings || {}
  return Object.entries(mappings).map(([systemField, originalField]) => ({
    source: originalField,           // 原始列名（文件中的列名）
    target: systemField,             // 系统字段名（英文名）
    description: fieldDict[systemField] || systemField  // 字段描述（中文）
  }))
})

const handleTypeSelect = (type) => {
  currentDataType.value = type
}

const refreshList = () => {
  allTemplates.value = TemplateManager.getAllTemplates()
}

const handleView = (tpl) => {
  currentTemplate.value = tpl
  dialogVisible.value = true
}

const handleDelete = (tpl) => {
  if (confirm(`确定要删除模版 "${tpl.name}" 吗？`)) {
    const res = TemplateManager.deleteUserTemplate(tpl.id)
    if (res.success) {
      refreshList()
    } else {
      alert(res.message)
    }
  }
}

onMounted(() => {
  refreshList()
})
</script>

<style scoped>
.template-manage-container {
  display: flex;
  height: 100%;
  background: #f5f7fa;
}

.template-main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.btn-secondary {
  padding: 6px 12px;
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.btn-secondary:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.template-list-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 50px;
  color: #909399;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.template-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.02);
  display: flex;
  flex-direction: column;
  gap: 10px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-name {
  font-size: 15px;
  color: #303133;
}

.badge {
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 4px;
}

.badge-system {
  background: #e6f7ff;
  color: #1890ff;
}

.badge-user {
  background: #f6ffed;
  color: #52c41a;
}

.card-body {
  font-size: 13px;
  color: #606266;
}

.info-item {
  margin-bottom: 4px;
}

.example-text {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-footer {
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.btn-primary-outline {
  padding: 4px 10px;
  font-size: 12px;
  color: #409eff;
  background: white;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary-outline:hover {
  background: #ecf5ff;
  border-color: #409eff;
}

.btn-danger-outline {
  padding: 4px 10px;
  font-size: 12px;
  color: #ff4d4f;
  background: white;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  cursor: pointer;
}

.btn-danger-outline:hover {
  background: #fff1f0;
  border-color: #ff4d4f;
}

.template-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  font-size: 13px;
  color: #606266;
}

.info-item .label {
  color: #909399;
  margin-right: 4px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}
</style>
